<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace builder\helper;

/**
 * 其他
 * @author cleverstone
 * @since ym2.0
 */
class Util
{
    /**
     * 文件大小单位转换
     * @param integer|string|float $size 大小
     * @param string $unit 单位，默认传入的大小单位是字节
     * @return string
     */
    public static function fileUnit($size, $unit = 'B')
    {
        settype($size, 'float');

        if ($size > 1024) {
            if (strncasecmp($unit, 'B', 1) === 0) {
                $nextUnit = 'KB';
            } elseif (strncasecmp($unit, 'K', 1) === 0) {
                $nextUnit = 'MB';
            } elseif (strncasecmp($unit, 'M', 1) === 0) {
                $nextUnit = 'GB';
            } elseif (strncasecmp($unit, 'G', 1) === 0) {
                $nextUnit = 'TB';
            } elseif (strncasecmp($unit, 'T', 1) === 0) {
                $nextUnit = 'PB';
            } else {
                return Math::floor($size) . $unit;
            }

            return self::fileUnit(Math::div($size, 1024), $nextUnit);
        }

        return Math::floor($size) . $unit;
    }

    /**
     * 生成全局唯一ID
     * @return string
     */
    public static function createGUID()
    {
        $charId = md5(uniqid(mt_rand(), true));
        $hyphen = chr(45);
        $uuid = substr($charId, 6, 2) . substr($charId, 4, 2) .
            substr($charId, 2, 2) . substr($charId, 0, 2) . $hyphen
            . substr($charId, 10, 2) . substr($charId, 8, 2) . $hyphen
            . substr($charId, 14, 2) . substr($charId, 12, 2) . $hyphen
            . substr($charId, 16, 4) . $hyphen . substr($charId, 20, 12);

        return $uuid;
    }

    /**
     * 根据两点的经纬度获取其直线距离
     * @param float $latx 地点x纬度
     * @param float $laty 地点y纬度
     * @param float $lngx 地点x经度
     * @param float $lngy 地点y经度
     * @param integer $precision 返回结果的精度,默认:2
     * @return float 两点之间的直线距离(km)
     */
    public static function getDistanceByRect($latx, $laty, $lngx, $lngy, $precision = 2)
    {
        return Math::floor(acos((sin(deg2rad($latx)) * sin(deg2rad($laty)) + cos(deg2rad($latx)) * cos(deg2rad($laty)) * cos(deg2rad($lngx) - deg2rad($lngy)))) * 6371.393, $precision);
    }
}